package top.codetheory.thread._001_打断;

import lombok.extern.slf4j.Slf4j;

/**
 * @author: CodeTheory
 * @since: 2024/5/1 上午7:34
 **/
@Slf4j
public class _007_打断Wait状态的线程 {

    public static void main(String[] args) throws InterruptedException {
//        test1();
        test2();
    }

    /**
     * 打断正常的线程 <br>
     * <img src="https://gitee.com/codetheory/img-on1/raw/master/img01/1714520958801-2024-5-107:49:19.png"  />
     */
    private static void test1() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            Thread currentThread = Thread.currentThread();
            for (int i = 0; i < 100; i++) {
                log.info("{}-{}",i,currentThread.isInterrupted());
            }
        }, "t1");

        t1.start();
        Thread.sleep(1);

        t1.interrupt();

        log.info("main end");
    }

    /**
     * 打断wait状态的线程，可以看到在打断之后还是可以运行的，所以打断不会切换线程的状态 <br>
     * <img src="https://gitee.com/codetheory/img-on1/raw/master/img01/1714521906235-2024-5-108:05:07.png"  />
     */
    private static void test2() {
        Object lock = new Object();

        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    log.info("打断状态: {}", Thread.currentThread().isInterrupted());
//                    e.printStackTrace();
                }
                for (int i = 0; i < 10; i++) {
                    log.info("{}-打断之后", i);
                }
            }
        }, "t1");

        t1.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        t1.interrupt();

        System.out.println("main end");
    }
}